var _startX = 0; // mouse starting positions 
var _startY = 0; 
var _offsetX = 0; // current element offset 
var _offsetY = 0; 
var _dragElement; // needs to be passed from OnMouseDown to OnMouseMove
var _oldZIndex = 0; // we temporarily increase the z-index during drag
var _defPos = 0;
var _rotTemp=0; //maarab, kas viimane klikk pooras laeva, ja kui, siis mis suunas
var _isTurned = {};
var _isDeployed = 0;
// 0 jp, 1 us
var _side = 0;
//Lihtsusab ID paringuid
function id(id) 
{ 
	return document.getElementById(id);
}
//Otsib valja Inti.
function extractNumber(value) 
{ 
	var n = parseInt(value); 
	return n == null || isNaN(n) ? 0 : n; 
}
// Funktisioon, mis annab objekti absoluutse asukoha
function location(objID)
{
	var obj = id(objID);
	var curleft=0;
	var curtop=0;
	if (obj.offsetParent){
		do{
			curleft+=obj.offsetLeft;
			curtop+=obj.offsetTop;
		}while (obj=obj.offsetParent);
	}
	return [curleft,curtop];
}
//fikseerib absoluutse positsiooni
function fikPos(objID)
{
	var loc = location(objID);
	var obj = id(objID);
	obj.style.position="absolute";
	obj.style.left=loc[0]+'px';
	obj.style.top=loc[1]+'px';
	return loc;
}
//Annab lehekulje absoluutse ja suhtelise vasaku ulemise poole vahe
function scroll1()
{
	return [$("html").offset().left,$("html").offset().top];
}
// Keerab laeva umber
function turnShip(target)
{
	idT=target.id;
	_rotTemp =1;
	var JQPar="img#"+target.id;
	if (_isTurned[idT]== null)
	{
		var height = $(JQPar).css('height');
		$(JQPar).css('height',$(JQPar).css('width'));
		$(JQPar).css('width',height);
		var uusSrc = String(target.src).split(".png");
		uusSrc = uusSrc[0]+"Rot.png";
		target.src=uusSrc;
		_isTurned[target.id]=1;
	}
	else
	{
		var height = $(JQPar).css('height');
		$(JQPar).css('height',$(JQPar).css('width'));
		$(JQPar).css('width',height);
		var vanaSrc = (String(target.src).split("Rot"));
		vanaSrc = vanaSrc[0]+".png";
		target.src=vanaSrc;
		_isTurned[target.id]=null;
	}
}
function paint(arr,color)
{
	if (arr ==0)
	{
		temp=[]
		for (j=1;j<=10;j++)
		{
			for (i=1;i<=10;i++)
			{
				temp[temp.length]=[j,i];
			}	
		}
		arr = temp;
	}
	for(j=0;j<arr.length;j++)
		{
		id(InttoS(arr[j])).style.backgroundColor =color;
		}
}
function onMouseDown(e)
{
	if (_isDeployed==0)
	{
		var target = e.target
		// Parem klikk keerab laeva
		if (((target.className=='fourDep') || (target.className=='threeDep')|| 
				(target.className=='twoDep') || (target.className=='oneDep')))
		{
			var loc =fikPos(target.id);
			var scrol = scroll1();
			_defPos = loc.slice(0);
			_defPos[0]-=scrol[0];
			_defPos[1]-=scrol[1];
			_dragElement = target;
			
			
			if (e.button==0)
			{
				
				_startX = e.clientX;
				_startY = e.clientY;
				_offsetX = extractNumber(loc[0]);
				_offsetY = extractNumber(loc[1]);
				oldZIndex = target.style.zIndex; 
				target.style.zIndex = 10000;
				document.onmousemove = onMouseMove;
				document.body.focus();
				return false;
			}
			if (e.button==2)
			{
				turnShip(target);
				
			}
		}
	}
}
function onMouseMove(e) 
{
	
	_dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px';
	_dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px'; 
}
function onMouseUp(e)
{ 
	if (_dragElement != null) 
	{ 
		
		_dragElement.style.zIndex="-1";
		//id('pealkiri').innerHTML=String(_illegal[InttoS([2,2])]);
		//Votame arvesse kui palju on veebilehte scrollitud esialgsest tipust eemale
		var scroll = scroll1();
		var id1= "#"+_dragElement.id;
		//Mis element kursori all on
		if (_isTurned[_dragElement.id]== null)
		{
			var element= document.elementFromPoint(extractNumber(_dragElement.style.left)+scroll[0]+($(id1).width()*0.15)
				,extractNumber(_dragElement.style.top)+scroll[1]+($(id1).height()*0.50));
		}
		else
		{
			var element= document.elementFromPoint(extractNumber(_dragElement.style.left)+scroll[0]+($(id1).width()*0.50)
					,extractNumber(_dragElement.style.top)+scroll[1]+($(id1).height()*0.15));
		}
		if ((element != null) && (element.className=="square"))
		{
			var valid = validator(element.id,_dragElement,_isTurned[_dragElement.id]);
			
			if (valid[0]==true)
			{
				
				var scroll = scroll1();
				var locEle = location(element.id);
				if (_isTurned[_dragElement.id]== null)
				{
					_dragElement.style.left=extractNumber(locEle[0])+'px';
					_dragElement.style.top=extractNumber(locEle[1])+($(".square").height()*0.3)+'px';
				}
				else
				{
					_dragElement.style.left=extractNumber(locEle[0])+($(".square").height()*0.30)+'px';
					_dragElement.style.top=extractNumber(locEle[1])+'px';
				}
				paint(valid[1],"red");
			
			}
			else
			{
				_dragElement.style.left=extractNumber(_defPos[0])+scroll[0]+'px';
				_dragElement.style.top=extractNumber(_defPos[1])+scroll[1]+'px';
				if (_rotTemp==1)
				{
					turnShip(_dragElement);
				}
			}

		}
		else if ((element != null) && (element.className=="shipDiv"))
		{
			//Vabastab all kinni olevad ruudud
			var toLegal =legalize(_dragElement.id);
			if (toLegal[0]==true)
			{				
				paint(toLegal[1],"#CCCCCC");
				if (isPositioned(_dragElement.id,_side)==true)
					{
						removePosition(_dragElement.id,_side)
					}
			}
		}
		else
		{
			_dragElement.style.left=extractNumber(_defPos[0])+scroll[0]+'px';
			_dragElement.style.top=extractNumber(_defPos[1])+scroll[1]+'px';
		}
		_rotTemp=0;
		_defPos = null;
		_dragElement.style.zIndex = _oldZIndex;
		document.onmousemove = null; 
		document.onselectstart = null; 
		_dragElement.ondragstart = null; 
		_dragElement = null; 
	}
}
function onContext(e)
{
	return false;
}
 function InitDragDrop() 
{ 
	 document.onmousedown = onMouseDown;
	 document.onmouseup = onMouseUp;
	 document.oncontextmenu = onContext;
}
 InitDragDrop();
 
$(document).ready(function() 
   {

$('.rsquare').click(function()
{
	if (_isDeployed==1)
	{
		$(this).find('.square1').css('background-color','#CCCCCC');
		if (isValid($(this).attr("id")))
    	{
    	$(this).css('background-color','#0000FF');
    	}
	}
});
$('#rdyBtn').click(function()
{	
	if (_isDeployed==0)
	{
		if (isDeployed(_side)==10)
		{
			_isDeployed=1;
			$(this).css('background-color','green');
			paint(0,'#CCCCCC');
		}
		else{
			$(this).effect("highlight", {color:"red"}, 1000);
		}
	}
	else
	{
		_isDeployed=0;	
		paint(allIllegal(),'red');
		$(this).css('background-color','');
	}
});
	
//Hektel maas, kuna USA eest kaib arvuti
/*$('.square').click(function()
{
    $(this).find('.square').css('background-color','#CCCCCC');
    if (isValid($(this).id())
    {
    	$(this).css('background-color','#0000FF');
    }
	
});*/
});